package cn.tmall.servlet;

import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.tmall.bean.Category;
import cn.tmall.bean.Property;
import cn.tmall.bean.PropertyValue;
import cn.tmall.dao.CategoryDAO;
import cn.tmall.dao.PropertyDAO;
import cn.tmall.dao.PropertyValueDAO;
import cn.tmall.util.Page;

public class PropertyServlet extends BaseBackServlet{
	
	public String list(HttpServletRequest request,HttpServletResponse response,Page page){
		
		int cid = Integer.valueOf(request.getParameter("cid"));
		Category c = new CategoryDAO().get(cid);
		List<Property> ps = new PropertyDAO().list(cid,page.getStart(),page.getCount());
		int total = new PropertyDAO().getTotal(cid);
		page.setTotal(total);
		page.setParam("&cid="+c.getId());
        
        request.setAttribute("ps", ps);
        request.setAttribute("c", c);
        request.setAttribute("page", page);
         
        return "admin/listProperty.jsp";
	}
	
	public String add(HttpServletRequest request,HttpServletResponse response,Page page) throws UnsupportedEncodingException{
	
		String name = new String(request.getParameter("name").getBytes("ISO-8859-1"),"UTF-8");
		int cid = Integer.valueOf(request.getParameter("cid"));
		Property p = new Property();
		p.setName(name);
		p.setCategory(new CategoryDAO().get(cid));
		new PropertyDAO().add(p);
		System.out.println(name);
		return "@admin_property_list?cid="+cid; 
	}
	
	public String delete(HttpServletRequest request,HttpServletResponse response,Page page){
		int id = Integer.valueOf(request.getParameter("id"));
		Property p = new Property();
		p = new PropertyDAO().get(id);
		new PropertyDAO().delete(id);
		int cid = p.getCategory().getId();
		return "@admin_property_list?cid="+cid;
	}
	
	public String edit(HttpServletRequest request,HttpServletResponse response,Page page){
		int id = Integer.valueOf(request.getParameter("id"));
		Property p = new Property();
		p = new PropertyDAO().get(id);
		request.setAttribute("p", p);
		return "admin/editProperty.jsp";
	}
	
	public String update(HttpServletRequest request,HttpServletResponse response,Page page) throws UnsupportedEncodingException{
		int id = Integer.valueOf(request.getParameter("id"));
		int cid = Integer.valueOf(request.getParameter("cid"));
		String name = new String(request.getParameter("name").getBytes("ISO-8859-1"),"UTF-8");
		Property p = new Property();
		p.setId(id);
		p.setName(name);
		p.setCategory(new CategoryDAO().get(cid));
		new PropertyDAO().update(p);
		return "@admin_property_list?cid="+cid;
	}
}
